package com.qianya.system.face.web.patient.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.arcsoft.face.FaceInfo;
import com.arcsoft.face.toolkit.ImageFactory;
import com.arcsoft.face.toolkit.ImageInfo;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianya.model.common.JWTUtil;
import com.qianya.model.pojo.patient.qo.PatientFileInfoQO;
import com.qianya.model.pojo.patient.qo.PatientOxygenRecodeQO;
import com.qianya.model.pojo.patient.vo.PatientFileInfoPlanVO;
import com.qianya.model.pojo.patient.vo.PatientFileInfoRecodeVO;
import com.qianya.model.pojo.patient.vo.PatientFileInfoVO;
import com.qianya.system.face.config.RedisUtil;
import com.qianya.system.face.util.UserRamCache;
import com.qianya.system.face.web.patient.mapper.PatientFileInfoMapper;
import com.qianya.system.face.web.patient.model.PatientFileInfo;
import com.qianya.system.face.web.patient.model.PatientOxygen;
import com.qianya.system.face.web.patient.service.FaceEngineService;
import com.qianya.system.face.web.patient.service.IPatientFileInfoService;
import com.qianya.system.face.web.patient.service.IPatientOxygenService;
import com.qianya.util.DateUtils;
import com.qianya.util.FileUtil;
import com.qianya.util.SystemConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qianya.model.common.CommonResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qianya.model.common.ResultCode;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* <p>
*  患者档案服务实现类
* </p>
*
* @author lhl
* @since 2020-07-02
*/
@Service
public class PatientFileInfoServiceImpl extends ServiceImpl<PatientFileInfoMapper, PatientFileInfo> implements IPatientFileInfoService {


      @Autowired
      private FaceEngineService faceEngineService;
      @Autowired
      private IPatientOxygenService patientOxygenService;
      @Resource
      private PatientFileInfoMapper fileInfoMapper;
        /**
         * @desc
         * @author lhl
         * @date 2020-08-14 11:09
         * @return
        */
        @Override
        public CommonResult view(String fileId) {
            PatientFileInfo pfi=getById(fileId);
            PatientOxygen po=patientOxygenService
                    .getOne(new QueryWrapper<PatientOxygen>().eq("file_id",fileId).orderByDesc("create_time").last("limit 0,1"));
            if (po==null){
                return CommonResult.success(pfi);
            }
             pfi.setHeartRate(po.getHeartRate());
             pfi.setBloodOxygen(po.getBloodOxygen());
            return CommonResult.success(pfi);
        }

        /**
        *查找 患者档案
        * @author lhl
        * @since 2020-07-02
        */
        @Override
        public CommonResult find(PatientFileInfoQO fileInfo) {
            QueryWrapper<PatientFileInfo> queryWrapper=new QueryWrapper<>();
            queryWrapper.like(StrUtil.isNotBlank(fileInfo.getFilePatientName()),"file_patient_name",fileInfo.getFilePatientName())
                    .eq(StrUtil.isNotEmpty(fileInfo.getFileHospitalNum()),"file_hospital_num",fileInfo.getFileHospitalNum())
                    .gt(fileInfo.getFileAdmissionDate()!=null,"file_admission_date",fileInfo.getFileAdmissionDate())
                    .lt(fileInfo.getFileDischargeDate()!=null,"file_admission_date",fileInfo.getFileDischargeDate())
                    .orderByDesc("file_admission_date");
            IPage iPage = page(new Page<PatientFileInfo>(fileInfo.getPageNo(),fileInfo.getPageSize(),true),queryWrapper);

            return CommonResult.success(iPage);
        }
        /**
        * 新增 患者档案
        * @author lhl
        * @since 2020-07-02
        */
        public CommonResult create(PatientFileInfo patientFileInfo) {
            boolean b = save(patientFileInfo);
            if (b){
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"操作失败");
        }
        /**
        * 修改 患者档案
        * @author lhl
        * @since 2020-07-02
        */
        @Override
        public CommonResult renewal(PatientFileInfo patientFileInfo, HttpServletRequest request) {
            // 根据档案编号获取患者信息
            String fileId = patientFileInfo.getFileId();
            PatientFileInfo pfi = this.getById(fileId);
            if (pfi == null){
                return CommonResult.error(ResultCode.ERROR,"未查询到该编号的患者");
            }
            // 如果修改用户头像
            if (StringUtils.isNotEmpty(patientFileInfo.getFilePatientIcon())) {
                // 上传头像图片
                String path = FileUtil.base64UpLoad(patientFileInfo.getFilePatientIcon());
                if ("error".equals(path)) {
                    return  CommonResult.error(ResultCode.IMAGES_ExCEPTION,"图片格式错误");
                }
                String absolutePath = path.replace("\\statics", SystemConfig.filePath());
                File files = new File(absolutePath);
                ImageInfo rgbData = ImageFactory.getRGBData(files);
                List<FaceInfo> faceInfoList = faceEngineService.detectFaces(rgbData);
                if (CollectionUtil.isEmpty(faceInfoList)) {
                    return CommonResult.error(ResultCode.OTHER_EXCEPTION,"未识别到人脸");
                }
                byte[] feature = faceEngineService.extractFaceFeature(rgbData, faceInfoList.get(0));
                // 根据feature查询是否存在用户
                QueryWrapper<PatientFileInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("file_face_feature", feature);
                List<PatientFileInfo> existsPatientFileInfoList = this.list(queryWrapper);
                // 校验头像是否已存在 根据照片查询该患者是否存在档案编号 如果已存在且不是当前用户就返回
                if (existsPatientFileInfoList != null && existsPatientFileInfoList.size() > 0
                        && !fileId.equals(existsPatientFileInfoList.get(0).getFileId())) {
                    return  CommonResult.error(ResultCode.ERROR,"该患者已录入");
                }
                patientFileInfo.setFileFaceFeature(feature);
                patientFileInfo.setFilePatientIcon(path);
            }
            String oldIco = pfi.getFilePatientIcon().replace("\\statics", SystemConfig.filePath());
            patientFileInfo.setFileUpdateTime(new Date());
            patientFileInfo.setFileUpdateId(JWTUtil.getUserId(request.getHeader("token")));
            if (this.updateById(patientFileInfo)){
                FileUtil.delete(oldIco);
                UserRamCache.addUser(getById(patientFileInfo.getFileId()));
                return CommonResult.success();
            }
            return CommonResult.error(ResultCode.ERROR,"修改失败");
        }
    /**
     * @desc  根据his住院号同步患者信息
     * @author lhl
     * @date 2020-07-20 14:00F
     * @return
    */
    @Override
    public CommonResult<IPage<PatientFileInfoVO>> infoSync(String fileHospitalNum) {
        PatientFileInfo pfi=getOne(new QueryWrapper<PatientFileInfo>().eq("file_hospital_num",fileHospitalNum));
        if (pfi==null){
            return CommonResult.error(ResultCode.ERROR,"未查询到该编号的患者");
        }
        Map<String, String> map=new HashMap<String,String>();
        if (updateById(pfi)){
            return CommonResult.success();
        }
        return CommonResult.error(ResultCode.ERROR,"修改失败");

    }
    /**
     * @desc 服药进度
     * @author lhl
     * @date 2020-07-23 10:58
     * @return
    */
    @Override
    public CommonResult plan() {
        try{
            List<String> list= DateUtils.theThreeTimeQuantum();
            List<PatientFileInfoPlanVO> morning=fileInfoMapper.plan(list.get(0),list.get(1));
            List<PatientFileInfoPlanVO> noon=fileInfoMapper.plan(list.get(1),list.get(2));
            List<PatientFileInfoPlanVO> night=fileInfoMapper.plan(list.get(2),list.get(3));
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("night",night);
            map.put("noon",noon);
            map.put("morning",morning);
            return CommonResult.success(map);
        }catch (Exception e){
            return CommonResult.error(ResultCode.ERROR,"系统异常");
        }

    }
    /**
     * @desc  统计患者总数
     * @author lhl
     * @date 2020-07-24 11:56
     * @return
    */
    @Override
    public int patientCount(int type) {
        QueryWrapper<PatientFileInfo> queryWrapper=new QueryWrapper<PatientFileInfo>();
        List<String> timeList=DateUtils.theSameDay();
        if (type==1){
            queryWrapper.gt("file_update_time",timeList.get(0));
        }
        return count(queryWrapper);
    }
    /**
     * @desc 根据日期查询患者服药记录
     * @author lhl
     * @date 2020-08-04 15:49
     * @return
    */
    @Override
    public CommonResult dateRecode(PatientOxygenRecodeQO patientOxygenRecodeQO) {
        Integer pageNo=patientOxygenRecodeQO.getPageNo();
        String time=patientOxygenRecodeQO.getTime();

        Integer pageSize=patientOxygenRecodeQO.getPageSize();
        if (pageNo==1 ||pageNo==0){
            pageNo=0;
        }else {
            pageNo=pageSize*(pageNo-1);
        }
        Date date=null;
        if ("".equals(time)){
            date=new Date();
        }else {
            date=DateUtils.parse(time,"yyyy-MM-dd");
        }
        List<String> list=DateUtils.todayPutMedicTime(date);
        if ("".equals(time)){
            Date newdata=this.timeTrans(new Date());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH");
            list.set(1,sdf.format(newdata));
        }
        patientOxygenRecodeQO.setPageNo(pageNo);
        patientOxygenRecodeQO.setPageSize(pageSize);
        List<PatientFileInfoRecodeVO> pfirList=fileInfoMapper.dateRecode(list.get(0),list.get(1),patientOxygenRecodeQO);
        Integer count=fileInfoMapper.dateRecodeCount(list.get(0),list.get(1),patientOxygenRecodeQO);
        for (int i = 0; i <pfirList.size() ; i++) {
            pfirList.get(i).setFileTime(DateUtil.formatDate(date));
            if (pfirList.get(i).getBrState().indexOf("1")!=-1){
                pfirList.get(i).setBrState("1");
            }else if (pfirList.get(i).getBrState().indexOf("2")!=-1){
                pfirList.get(i).setBrState("2");
            }else {
                pfirList.get(i).setBrState("0");
            }
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("recode",pfirList);
        map.put("totol",count);
        map.put("pageNo",pageNo);
        map.put("pageSize",pageSize);
        return CommonResult.success(map);
    }
    /**
     * @desc 时间转换
     * @author lhl
     * @date 2020-07-24 15:43
     * @return
     */
    public Date timeTrans(Date time){
        SimpleDateFormat sdf=new SimpleDateFormat("HH");
        Calendar cal=Calendar.getInstance();
        cal.setTime(time);
        Integer hours=Integer.valueOf(sdf.format(time));
        if (hours<8){
            cal.set(Calendar.HOUR_OF_DAY, -6);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
        }else if (hours<12){
            cal.set(Calendar.HOUR_OF_DAY, 8);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
        }else if (hours<18){
            cal.set(Calendar.HOUR_OF_DAY, 12);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
        }else {
            cal.set(Calendar.HOUR_OF_DAY, 18);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
        }

        return cal.getTime();
    }
}
